package org.permission.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.permission.pojo.SysPermission;
import org.permission.pojo.SysRole;
import org.permission.pojo.SysUser;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class ProjectUtils {
	private static Class[] classes;// 要生成相应模块的实体类
	// 存储 FreeMarker 应用级设置的核心部分。同时，它也处理创建和 缓存 预解析模板(比如 Template 对象)的工作。
	private static Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
	private static Map<String, Object> model = new HashMap<>();// 模型数据
	// setter方法

	public static void setClasses(Class[] classes) {
		ProjectUtils.classes = classes;
	}

	/**
	 * FreeMarker框架的设置
	 */
	static {
		try {
			configuration.setDirectoryForTemplateLoading(new File("src/main/resources/templates"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 设置字节编码
		configuration.setDefaultEncoding("utf-8");
		// 准备模型数据
		model.put("projectName", "permission");
		model.put("jing", "#");
		model.put("dao", "$");
		
		classes = new Class[] {SysPermission.class};
	}
	
	public static void main(String[] args) throws Exception{
		generateMappers();
	}
	
	

	/**
	 * 生成dao接口
	 * 
	 * @throws Exception
	 */
	public static void generateDaoInterface() throws Exception {
		Template template = configuration.getTemplate("mapper.ftl");

		// 根据传入的 classes 来批量生成dao接口、
		if (classes == null) {
			return;
		}
		for (Class clazz : classes) {
			model.put("pojoName", clazz.getSimpleName()); // 获取到实体类的名称
			Field[] fields = clazz.getDeclaredFields(); // 获得某个类声明的所有字段
			String pkType = "Integer";
			for (Field field : fields) {
				if (field.getAnnotations().length > 0) { // 如果当前字段的注解数量大于0
					if (field.getAnnotations()[0].annotationType() == Resource.class) { // 如果第一个注解是Resource的话
						pkType = field.getType().getSimpleName();
					}
				}
			}
			model.put("pkType", pkType);

			// 输出到对应的目录
			File file = new File("src/main/java/org/aptech/shiro/permission/dao/" + clazz.getSimpleName() + "Dao.java");
			if (file.exists() == false) {
				file.createNewFile();
			}
			Writer out = new OutputStreamWriter(new FileOutputStream(file));
			template.process(model, out);

			System.out.println("generate" + clazz.getSimpleName() + "Dao.java success!");
		}

	}

	/**
	 * 生成 sql mapper files
	 * 
	 * @throws Exception
	 */
	public static void generateMappers() throws Exception {
		Template template = configuration.getTemplate("mapper.ftl");

		// 根据传入的 classes 来批量生成dao接口
		if (classes == null) {
			return;
		}
		for (Class clazz : classes) {
			model.put("pojoName", clazz.getSimpleName());
			// 根据类名自动计算出表名 SysUser -- sys_user
			StringBuffer sb = new StringBuffer(clazz.getSimpleName());

			char[] array = clazz.getSimpleName().toCharArray();
			for (int i = 1; i < array.length; i++) {
				char c = array[i];
				boolean isUpper = Character.isUpperCase(c);
				if (isUpper) {
					sb.insert(i, "_");
				}
			}
			model.put("table_name", sb.toString().toLowerCase());

			List<String> columnNames = new ArrayList<>();
			Field[] fields = clazz.getDeclaredFields();
			String pkType = "Integer";
			for (Field field : fields) {
				if (field.getAnnotations().length > 0 && field.getAnnotations()[0].annotationType() == Resource.class) {
					pkType = field.getType().getSimpleName();
				} else {
					if (field.getType() != List.class) {
						columnNames.add(field.getName());
					}
				}
			}
			model.put("columnNames", columnNames);

			// 输出到对应目录
			File file = new File("src/main/resources/org/" + model.get("projectName") + "/mappers/"
					+ clazz.getSimpleName() + "Mapper.xml");

			System.out.println(file.getAbsolutePath());
			if (file.exists() == false) {
				file.createNewFile();
			}
			Writer out = new OutputStreamWriter(new FileOutputStream(file));
			template.process(model, out);

			System.out.println("generate" + clazz.getSimpleName() + "Mapper.xml success!");
		}
	}

}
